<?php
	class District_model extends MY_Model{
		
		public function __construct(){
			$this->load->database();
		}
		
		public function get_district($id=FALSE, $c_id=FALSE){			
			if($id === FALSE && $c_id === FALSE){
				$this->db->select('d.*, c.city');
				$this->db->from('district d');
				$this->db->join('city c', 'c.id = d.city_id', 'left');
				$this->db->limit($this->record_per_page, $this->limit);
				$query = $this->db->get();				
				return $query->result_array();
			}
			elseif($id===FALSE && $c_id != FALSE){			
				$this->db->select('d.*, c.city');
				$this->db->from('district d');
				$this->db->join('city c', 'c.id = d.city_id', 'left');
				$this->db->where('d.city_id = '.$c_id, NULL, FALSE);
				$this->db->limit($this->record_per_page, $this->limit);				
				$query = $this->db->get();
				return $query->result_array();
			}
			else{
				$this->db->limit($this->record_per_page, $this->limit);
				$query = $this->db->get_where('district', array('id' => $id));
				return $query->row_array();
			}
		}		
		
		public function get_district_list($c_id=FALSE){
			if($c_id!=FALSE)
				$query = $this->db->get_where('district', array('city_id' => $c_id));
			else
				$query = $this->db->get('district');
			return $query->result_array();
		}
		
		public function get_total(){
			return count($this->get_district_list());
		}
		
		public function get_total_search($src=FALSE){
			$this->db->select('d.*, c.city');
			$this->db->from('district d');
			$this->db->join('city c', 'c.id = d.city_id', 'left');
			$this->db->like('name', $src);				
			$query = $this->db->get();				
			return $query->num_rows();
		}
		
		public function get_total_filter($c_id=FALSE){
			$this->db->select('d.*, c.city');
			$this->db->from('district d');
			$this->db->join('city c', 'c.id = d.city_id', 'left');
			$this->db->where('d.city_id = '. $c_id, NULL, FALSE);			
			$query = $this->db->get();
			return $query->num_rows();
		}
		
		public function search($src=FALSE){
			$this->db->select('d.*, c.city');
			$this->db->from('district d');
			$this->db->join('city c', 'c.id = d.city_id', 'left');
			$this->db->like('name', $src);		
			$this->db->limit($this->record_per_page, $this->limit);
			$query = $this->db->get();				
			return $query->result_array();
		}
		
		public function save(){
			$id 	= $this->input->post('id');
			
			$data = array(
				"name" 		=> $this->input->post('name'),	
				"city_id"	=> $this->input->post('city_id')
			);
			if(empty($id))
				return $this->db->insert('district', $data);
			else{
				$this->db->where('id', $id);
				return $this->db->update('district', $data);
			}
		}
		
		public function delete($id){
			$this->db->where('id', $id);
			$this->db->delete('district');			
		}		
	}
?>